# This function converts connectivity matrices into a "long" format:

# Input: Either a single matrix, or a list of matrices
# Output: A matrix containing the dyadic information.  If the input was a list of matrices, this will contain an additional column specifying the matrix attribute (e.g., year)

matrix2dyads<-function(connectivitymatrix){
	
	# first define the function that converts single matrices into dyads.  This will be used as necessary later.
	convert.matrix<-function(singlematrix){
	
		# deal with matrices with no row or column names:
		if (is.null(rownames(singlematrix))) rownames(singlematrix)<-1:nrow(singlematrix)
		if (is.null(colnames(singlematrix))) colnames(singlematrix)<-1:ncol(singlematrix)
		
		dyads<-as.data.frame(matrix(NA, nrow=nrow(singlematrix)*ncol(singlematrix), ncol=3))
		colnames(dyads)<-c("row","column","value")
		dyads[,1]<-rep(rownames(singlematrix), times=ncol(singlematrix))
		dyads[,2]<-rep(colnames(singlematrix), each=nrow(singlematrix))
		dyads[,3]<-as.vector(singlematrix)
		dyads
		
		} # close convert.matrix function
	
	# now determine whether the input is a single matrix or a list of matrices:
	if (is.matrix(connectivitymatrix)) output<-convert.matrix(connectivitymatrix)
	
	if (is.list(connectivitymatrix)){
		
		# deal with missing item names:
		if (is.null(names(connectivitymatrix))) names(connectivitymatrix)<-1:length(connectivitymatrix)
		
		output<-NULL
		
		# now loop through the matrices in the list:
		for (i in 1:length(connectivitymatrix)){
			matrix.current<-connectivitymatrix[[i]]
			name.current<-names(connectivitymatrix)[i]
			dyads.current<-convert.matrix(matrix.current)
			dyads.current<-cbind(name.current, dyads.current)
			colnames(dyads.current)[1]<-"matrix"
			output<-rbind(output,dyads.current)
			
			# report progress:
			cat(paste("\n Completed matrix",i,"of",length(connectivitymatrix)))
			
			} # close i loop
		
		} # close is.list condition
	
	#return output
	invisible(output)
	
	} # close matrix2dyads function
	
